package com.godenwater.web.manager;

import com.godenwater.core.spring.Application;
import com.godenwater.core.spring.BaseDao;
import com.godenwater.framework.config.SpringUtils;
import com.godenwater.web.rtu.model.RtuStationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测站数据管理，存储最新的测站数据，以备检查
 * 
 * @author admin
 *
 */
public class StationDataManager {

	/** Lock object for synchronized session count updates. */
	private Object m_lock;

	@Autowired
	private BaseDao baseReadDao;

	private static StationDataManager instance = null;

	private Map<String, RtuStationData> mStations = new HashMap<String, RtuStationData>();

	private StationDataManager() {
		// create a lock object for the PropManager
		m_lock = new Object();
	}

	public static synchronized StationDataManager getInstance() {
		if (instance == null) {
			instance = new StationDataManager();
		}
		return instance;
	}

	public void init() {

		if (baseReadDao == null) {
			baseReadDao = SpringUtils.getBean("baseReadDao");
		}

		String sql = "select * from rtu_message_new a left join rtu_station  b ON a.stcd = b.stcd";

		List<RtuStationData> stationList = baseReadDao.getJdbcTemplate().query(
				sql, new RowMapper<RtuStationData>() {

					public RtuStationData mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						RtuStationData station = new RtuStationData();

						station.setStcd(rs.getString("STCD"));
						station.setRain60(rs.getString("F26"));//降水量累计值
						station.setRain5(rs.getString("F20"));//当前降水量
						station.setRiver(rs.getString("F37"));

						return station;
					}
				});

		System.out.println(">> 数据处理模块，加载测站最新数据完成，共加载 " + stationList.size() + " 个测站信息。");
	}

	public RtuStationData getStation(String stcd) {
		return this.mStations.get(stcd);
	}

	public void store(RtuStationData station) {
		synchronized (m_lock) {

			mStations.put(station.getStcd(), station);
		}
	}

	public void update(RtuStationData station) {
		synchronized (m_lock) {
			
			String stcd = station.getStcd();

			if (mStations.containsKey(stcd)) {
				mStations.remove(stcd);
			}
			this.mStations.put(stcd, station);
		}
	}

	public void destroyed(RtuStationData station) {
		synchronized (m_lock) {
			
			String stcd = station.getStcd();

			if (mStations.containsKey(stcd)) {
				this.mStations.remove(stcd);
			}

		}
	}

}
